package android.SettingsTest;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XmlReader {
	
	private File f;
	public XmlReader(File f){
		this.f = f;
	}
	
	
	public HashMap<String, String> read(){
		HashMap<String, String> hash = new HashMap<String, String>();
		try {
			FileInputStream fIn = new FileInputStream(f);
			Document doc = parseFile(fIn);
			NodeList vis = doc.getElementsByTagName("preference");
			for (int i = 0; i < vis.getLength(); i++) {
				// Get element
				if (vis.item(i).getNodeType() == Document.ELEMENT_NODE) {

					String Name = ((Element) vis.item(i)).getAttribute("name");
					//String Type = ((Element) vis.item(i)).getAttribute("type");
					String Default = ((Element) vis.item(i))
							.getAttribute("defaultValue");

					hash.put(Name, Default);
					System.out.println(Name + "   " + Default);
				}
			}
			fIn.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FactoryConfigurationError e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return hash;
	}

	public Document parseFile(FileInputStream in) throws FactoryConfigurationError,
			ParserConfigurationException, SAXException, IOException {

		BufferedInputStream bis = new BufferedInputStream(in);

		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(bis);

		return doc;
	}
	
//	private void schrijf(NodeList list) {
//		System.out.println("XML Elements: ");
//		for (int i = 0; i < list.getLength(); i++) {
//			// Get element
//			if (list.item(i).getNodeType() == Document.ELEMENT_NODE) {
//
//				Element element = (Element) list.item(i);
//				System.out.println(element.getNodeName());
//
//			}
//		}
//	}
}
